// 将函数外部导出，new Promise对象，对象有两个参数一个是resolv, 一是reject, 然后发起请求
// 对象中的扩展运算符(...)用于取出参数对象中的所有可遍历属性，拷贝到当前对象之中


// 发送请求次数
let ajacTimes = 0
export const request = (params) => {
    // 判断url中是否带有/my/ 请求的是私有路径。带上header token
    let header = {...params.header }
    if (params.url.includes('/wechat/')) {
        // 拼接header 带上token 
        //header['Authorization'] = wx.getStorageSync("token");
        header['content-type'] = 'application/x-www-form-urlencoded'
    }
    if (params.url.includes('/picture/')) {
        header['content-type'] = 'application/x-www-form-urlencoded'
    }
    if (wx.getStorageSync("sessionid")) {
        console.log(header['cookie'] = wx.getStorageSync('sessionid'))
        header['cookie'] = wx.getStorageSync('sessionid')
    }


    ajacTimes++
    wx.showLoading({
        title: "正在加载",
        mask: true,
    });
    // 定义公共的url
    const baseUrl = "https://ship.gzcskj.cn/"
        // const baseUrl = 'http://192.168.1.3:8000/'
    return new Promise((resolve, reject) => {
        // 成功是resolve, 失败reject
        wx.request({
            ...params,
            header: header,
            url: baseUrl + params.url,
            success: (result) => {
                if (result.header['Set-Cookie'] != null) {
                    console.log(result.header['Set-Cookie'])
                    wx.setStorageSync("sessionid", result.header["Set-Cookie"])
                }
                resolve(result.data);

            },
            fail: (err) => {
                reject(err);
            },
            // 无论成功还是失败都会执行complete函数
            complete: () => {
                ajacTimes--;
                if (ajacTimes === 0) {
                    wx.hideLoading();
                }
            }
        });
    })
}